// src/views/mine.js
import React, { useState, useEffect } from "react";
import styles from "../css/Mine.module.css"; // 假设使用 CSS Modules
import { useNavigate, Link } from "react-router-dom";
import axios from "axios";
import { Loading } from "react-vant";

export default function Mine() {
  const user = JSON.parse(sessionStorage.getItem("user"));
  console.log(user);
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [cartItems, setCartItems] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [indexRes, cartRes] = await Promise.all([
          axios.post("/mobile/index"),
          axios.post("/mobile/shopping", { id: "79" }),
        ]);
        setData(indexRes.data.data);
        setCartItems(cartRes.data.data || []); // 确保默认是数组
      } catch (err) {
        console.error("请求失败:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

    // 移出购物车
    const handleRemoveFromCart = (productId, e) => {
      console.log(productId);
      console.log(cartItems);
      for (let i in cartItems) {
        if (cartItems[i].commodity_id == productId) {
          axios
            .post("mobile/shopping/del", {
              // 根据需求传递商品ID
              id: cartItems[i].id,
            })
            .then((response) => {
              console.log("商品已成功移出购物车", response.data);
              // 可根据实际返回的数据更新UI
            })
            .catch((error) => {
              console.error("接口请求失败", error);
            });
        }
      }
    };
  
    // 加入购物车
    const handleAddToCart = (product, e) => {
      axios
      .post("mobile/shopping/add", {
        // 根据需求传递商品ID
        commodity_id: product.id,
        user_id:JSON.parse(sessionStorage.getItem("user")).id,
        num:1
      })
      .then((response) => {
        console.log("商品已成功移出购物车", response.data);
        // 可根据实际返回的数据更新UI
      })
      .catch((error) => {
        console.error("接口请求失败", error);
      });
      e.stopPropagation(); // 阻止事件冒泡
      setCartItems([...cartItems, product]);
    };
  
    
  
    // 判断商品是否在购物车
    const isInCart = (productId) => {
      return cartItems.some(
        (item) => String(item.commodity_id) === String(productId)
      );
    };
  

  if (loading) {
    return (
      <Loading
        style={{
          display: "inline-flex",
          position: "fixed",
          left: "50%",
          top: "50%",
          transform: "translate(-50%, -50%)",
        }}
        size="24px"
        vertical
      >
        加载中...
      </Loading>
    );
  }
  console.log(data);
  
  return (
    <div className={styles.mineContainer}>
      {/* 用户信息卡片 */}
      <div className={styles.userCard}>
        <div className={styles.userInfo}>
          <div className={styles.avatar}>
            {/* 这里放头像图片 */}
            <div className={styles.avatarPlaceholder}></div>
          </div>
          <div className={styles.userText}>
            <p className={styles.userName}>
              {user.name == null ? "用户9527" : user.name}
            </p>
            <p className={styles.userId}>{user.id}</p>
          </div>
        </div>

        <div className={styles.balanceInfo}>
          <div className={styles.balanceItem}>
            <p className={styles.balanceLabel}>余额(元)</p>
            <p className={styles.balanceValue}>¥1243.23</p>
          </div>
          <div className={styles.balanceItem}>
            <p className={styles.balanceLabel}>总收益(元)</p>
            <p className={styles.balanceValue}>¥3341</p>
          </div>
          <div className={styles.balanceItem}>
            <p className={styles.balanceLabel}>可用收益(元)</p>
            <p className={styles.balanceValue}>¥741</p>
          </div>
        </div>
      </div>

      {/* 我的订单 */}
      <div className={styles.section}>
        <div className={styles.sectionHeader}>
          <h3 className={styles.sectionTitle}>我的订单</h3>
          <Link to="/Order">
            <span className={styles.viewAll}>全部订单 &gt;</span>
          </Link>
        </div>
        <div className={styles.orderStatus}>
          <div className={styles.statusItem}>
            <div className={styles.statusIcon}>
              <img src={require("../img/Pending payment.png")} alt="" />
            </div>
            <p>待付款</p>
          </div>
          <div className={styles.statusItem}>
            <div className={styles.statusIcon}>
              <img src={require("../img/To be received.png")} alt="" />
            </div>
            <p>待收货</p>
          </div>
          <div className={styles.statusItem}>
            <div className={styles.statusIcon}>
              <img src={require("../img/appraise.png")} alt="" />
            </div>
            <p>待评价</p>
          </div>
          <div className={styles.statusItem}>
            <div className={styles.statusIcon}>
              <img src={require("../img/off the stocks.png")} alt="" />
            </div>
            <p>已完成</p>
          </div>
          <div className={styles.statusItem}>
            <div className={styles.statusIcon}>
              <img src={require("../img/Exchanges.png")} alt="" />
            </div>
            <p>退换货</p>
          </div>
        </div>
      </div>

      {/* 我的服务 */}
      <div className={styles.section} style={{ marginTop: "10px" }}>
        <div className={styles.serviceGrid}>
          <div className={styles.serviceItem}>
            <div className={styles.serviceIcon}>
              <img src={require("../img/purse.png")} alt="" />
            </div>
            <p>我的钱包</p>
          </div>
          <div className={styles.serviceItem}>
            <div className={styles.serviceIcon}>
              <img src={require("../img/retail store.png")} alt="" />
            </div>
            <p>分销中心</p>
          </div>
          <div className={styles.serviceItem}>
            <div className={styles.serviceIcon}>
              <img src={require("../img/Delivery address.png")} alt="" />
            </div>
            <p>收货地址</p>
          </div>
          <div className={styles.serviceItem}>
            <div className={styles.serviceIcon}>
              <img src={require("../img/sidekick.png")} alt="" />
            </div>
            <p>邀请好友</p>
          </div>
        </div>
      </div>

       {/* 商品瀑布流 - 关键修改部分 */}
       <div className={styles.commodity}>
        {data.commodity?.map((product) => (
          <div
            key={product.id}
            onClick={() => navigate(`/details/${product.id}`)}
            className={styles.waterfall_box}
          >
            <img
              src={`http://jingxun.kuxia.top/${product.image}`}
              alt={product.title}
            />
            <p className={styles.goods_name}>{product.title}</p>
            <div className={styles.commodity_price}>
              <p className={styles.commodity_price_font}>
                <span className={styles.hot_goods_price_font}>￥</span>
                {product.price}
              </p>
              {isInCart(product.id) ? (
                <img
                  src={require("../img/check-circle.png")}
                  onClick={(e) => handleRemoveFromCart(product.id, e)}
                  alt="已在购物车"
                  className={styles.cartButton}
                />
              ) : (
                <img
                  onClick={(e) => handleAddToCart(product, e)}
                  src={require("../img/accretion.png")}
                  alt="加入购物车"
                  className={styles.cartButton}
                />
              )}
            </div>
          </div>
        ))}
      </div>


      {/* 底部导航栏 */}
      <div className={styles.bottom_navigation}>
        <div className={styles.bottom_navigation_option}>
          <Link to="/home">
            <img src={require("../img/home.png")} alt="" />
            <p>首页</p>
          </Link>
        </div>
        <div className={styles.bottom_navigation_option}>
          <img src={require("../img/list_bulleted.png")} alt="" />
          <p>分类</p>
        </div>
        <div className={styles.bottom_navigation_option}>
          <Link to="/Shopping">
            <img src={require("../img/shopping cart.png")} alt="" />
            <p>购物车</p>
          </Link>
        </div>
        <div className={styles.bottom_navigation_option}>
          <img
            className={styles.navigation_active}
            src={require("../img/person.png")}
            alt=""
          />
          <p className={styles.navigation_active}>我的</p>
        </div>
      </div>
    </div>
  );
}
